"""Migrates assignee and creator emails to participants.

Revision ID: 5693756fd192
Revises: 9eaa2a392dae
Create Date: 2020-05-05 14:34:23.108821

"""
from alembic import op
import sqlalchemy as sa

from dispatch.participant.flows import add_participant
from dispatch.task import service as task_service
from dispatch.individual.models import IndividualContact
from dispatch.plugins.dispatch_google.config import GOOGLE_DOMAIN


# revision identifiers, used by Alembic.
revision = "5693756fd192"
down_revision = "9eaa2a392dae"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    bind = op.get_bind()
    session = sa.orm.Session(bind=bind)

    tasks = bind.execute("select incident_id, creator, assignees, id from task")

    op.create_table(
        "task_assignees",
        sa.Column("participant_id", sa.Integer(), nullable=False),
        sa.Column("task_id", sa.Integer(), nullable=False),
        sa.ForeignKeyConstraint(
            ["participant_id"],
            ["participant.id"],
        ),
        sa.ForeignKeyConstraint(
            ["task_id"],
            ["task.id"],
        ),
        sa.PrimaryKeyConstraint("participant_id", "task_id"),
    )
    op.add_column("task", sa.Column("creator_id", sa.Integer(), nullable=True))
    op.create_foreign_key(None, "task", "participant", ["creator_id"], ["id"])

    op.drop_column("task", "creator")
    op.drop_column("task", "assignees")

    for incident_id, creator, assignees, id in tasks:
        print(f"Migrating task: {incident_id} {creator} {assignees}")
        emails = [e.strip() for e in assignees.split(",")]
        assignee_participants = []
        for e in emails:
            assignee_participants.append(add_participant(e, incident_id, db_session=session))

        # fetch creator email
        creator = session.query(IndividualContact).filter(IndividualContact.name == creator).first()

        creator_email = f"dispatch@{GOOGLE_DOMAIN}"
        if creator:
            creator_email = creator.email
        creator_participant = add_participant(creator_email, incident_id, db_session=session)

        task = task_service.get(db_session=session, task_id=id)
        task.creator = creator_participant
        task.assignees = assignee_participants
        session.add(task)
        session.commit()

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, "task", type_="foreignkey")
    op.drop_column("task", "creator_id")
    op.drop_table("task_assignees")

    op.add_column("task", sa.Column("assignees", sa.VARCHAR(), nullable=True))
    op.add_column("task", sa.Column("creator", sa.VARCHAR(), nullable=True))
    # ### end Alembic commands ###
